<template>
    <div class="user-profile-container">
        <div class="user-profile-header">
            <h2>用户管理</h2>
            <p>管理您的个人信息</p>
        </div>

        <div class="user-profile-content">
            <!-- 用户信息表单 -->
            <div class="profile-form-card">
                <h3>基本信息</h3>

                <!-- 头像上传区域 -->
                <div class="avatar-section">
                    <div class="avatar-uploader">
                        <label for="avatar-upload">
                            <div class="avatar-preview">
                                <img
                                        :src="avatarUrl"
                                        alt="用户头像"
                                        class="avatar-img"
                                        @error="handleAvatarError"
                                />
                                <div class="avatar-upload-overlay">
                                    <i class="icon-upload"></i>
                                    <span>更换头像</span>
                                </div>
                            </div>
                        </label>
                        <input
                                id="avatar-upload"
                                type="file"
                                accept="image/*"
                                class="avatar-input"
                                @change="handleAvatarUpload"
                                :disabled="isAvatarUploading"
                        />
                    </div>
                    <p class="avatar-hint">点击更换头像，支持JPG、PNG格式，不超过2MB</p>
                    <div v-if="isAvatarUploading" class="avatar-upload-progress">
                        <div class="progress-bar"></div>
                    </div>
                    <div v-if="avatarUploadError" class="error-message small">{{ avatarUploadError }}</div>
                </div>

                <form @submit.prevent="updateUserInfo">
                    <div class="form-group">
                        <label for="username">用户名</label>
                        <input
                                type="text"
                                id="username"
                                v-model="userInfo.username"
                                class="form-control"
                                disabled
                        />
                    </div>

                    <div class="form-group">
                        <label for="nickname">昵称</label>
                        <input
                                type="text"
                                id="nickname"
                                v-model="userInfo.nickname"
                                class="form-control"
                                placeholder="请输入昵称"
                        />
                    </div>

                    <div class="form-group">
                        <label for="phone">手机号</label>
                        <input
                                type="tel"
                                id="phone"
                                v-model="userInfo.phone"
                                class="form-control"
                                placeholder="请输入手机号"
                                pattern="^1[3-9]\d{9}$"
                        />
                    </div>

                    <div class="form-group">
                        <label for="password">修改密码（可选）</label>
                        <input
                                type="password"
                                id="password"
                                v-model="password"
                                class="form-control"
                                placeholder="留空表示不修改密码"
                        />
                    </div>

                    <div class="form-group">
                        <label for="confirmPassword">确认密码</label>
                        <input
                                type="password"
                                id="confirmPassword"
                                v-model="confirmPassword"
                                class="form-control"
                                placeholder="请再次输入新密码"
                        />
                    </div>

                    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
                    <div v-if="successMessage" class="success-message">{{ successMessage }}</div>

                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary" :disabled="isLoading">
                            {{ isLoading ? '保存中...' : '保存修改' }}
                        </button>
                    </div>
                </form>
            </div>

            <!-- 安全操作 -->
            <div class="security-actions-card">
                <h3>安全操作</h3>
                <button class="btn btn-danger logout-button" @click="handleLogout">
                    退出登录
                </button>
            </div>
        </div>
    </div>
</template>

<script>
import {ref, onMounted} from 'vue';
import {useRouter} from 'vue-router';
import {getUserInfo as fetchUserInfo, logout as logoutService, getCurrentUserId} from '../services/authService';
import axios from 'axios';

// 创建axios实例，与authService.js保持一致的配置
const api = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
});

// 请求拦截器，添加token
api.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 添加响应拦截器，与authService.js保持一致
api.interceptors.response.use(
    response => {
        // 直接返回response.data，这样可以直接访问code和data
        return response.data;
    },
    error => {
        console.error('API请求错误:', error);
        // 处理401未授权错误
        if (error.response && error.response.status === 401) {
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            router.push('/login');
        }
        return Promise.reject(error);
    }
);

// 创建用于文件上传的axios实例（不需要设置Content-Type，让浏览器自动设置）
const fileUploadApi = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 10000
});

// 为文件上传实例添加请求拦截器
fileUploadApi.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 为文件上传实例添加响应拦截器
fileUploadApi.interceptors.response.use(
    response => {
        // 直接返回response.data，与后端保持一致
        return response.data;
    },
    error => {
        console.error('文件上传错误:', error);
        // 处理401未授权错误
        if (error.response && error.response.status === 401) {
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            router.push('/login');
        }
        return Promise.reject(error);
    }
);

export default {
    name: 'UserProfileView',
    setup() {
        const router = useRouter();
        const userInfo = ref({});
        const password = ref('');
        const confirmPassword = ref('');
        const isLoading = ref(false);
        const errorMessage = ref('');
        const successMessage = ref('');

        // 新增：头像相关状态
        const avatarUrl = ref('');
        const isAvatarUploading = ref(false);
        const avatarUploadError = ref('');

        // 获取用户信息
        const loadUserInfo = async () => {
            try {
                isLoading.value = true;
                const userData = fetchUserInfo();

                // 从本地存储获取的用户信息可能不完整，我们向后端请求完整信息
                if (userData && userData.id) {
                    const response = await api.get(`/user/user/${userData.id}`);
                    if (response.code === 1) {
                        userInfo.value = response.data;
                        // 设置头像URL
                        if (userInfo.value.avatar) {
                            avatarUrl.value = userInfo.value.avatar;
                        } else {
                            // 使用默认头像
                            avatarUrl.value = '/imgs/default-avatar.png';
                        }
                    }
                } else {
                    // 如果本地没有用户信息，直接使用getCurrentUserId()获取ID
                    const userId = getCurrentUserId();
                    if (userId) {
                        const response = await api.get(`/user/user/${userId}`);
                        if (response.code === 1) {
                            userInfo.value = response.data;
                            // 设置头像URL
                            if (userInfo.value.avatar) {
                                avatarUrl.value = userInfo.value.avatar;
                            } else {
                                // 使用默认头像
                                avatarUrl.value = '/imgs/default-avatar.png';
                            }
                        }
                    }
                }
            } catch (error) {
                errorMessage.value = '获取用户信息失败：' + (error.message || '未知错误');
                console.error('获取用户信息失败:', error);
            } finally {
                isLoading.value = false;
            }
        };

        // 处理头像上传
        const handleAvatarUpload = async (event) => {
            const file = event.target.files[0];
            if (!file) return;

            // 验证文件大小（2MB）
            if (file.size > 2 * 1024 * 1024) {
                avatarUploadError.value = '头像文件大小不能超过2MB';
                setTimeout(() => {
                    avatarUploadError.value = '';
                }, 3000);
                return;
            }

            // 验证文件类型
            if (!file.type.startsWith('image/')) {
                avatarUploadError.value = '请上传图片类型的文件';
                setTimeout(() => {
                    avatarUploadError.value = '';
                }, 3000);
                return;
            }

            try {
                isAvatarUploading.value = true;
                avatarUploadError.value = '';

                const formData = new FormData();
                formData.append('file', file);

                // 发送文件上传请求到后端CommonController的/upload接口
                const response = await fileUploadApi.post('/common/upload', formData);

                // 后端返回的格式应该是：{"code": 1, "msg": "成功", "data": "文件URL"}
                if (response.code === 1) {
                    // 更新头像URL
                    const newAvatarUrl = response.data;
                    avatarUrl.value = newAvatarUrl;

                    // 调用用户信息更新API，将新的头像URL保存到用户信息中
                    await updateUserAvatar(newAvatarUrl);

                    // 显示成功消息
                    successMessage.value = '头像上传成功';
                    setTimeout(() => {
                        successMessage.value = '';
                    }, 3000);
                } else {
                    avatarUploadError.value = response.msg || '头像上传失败';
                    setTimeout(() => {
                        avatarUploadError.value = '';
                    }, 3000);
                }
            } catch (error) {
                avatarUploadError.value = '头像上传失败：' + (error.message || '网络错误');
                console.error('头像上传失败:', error);
                setTimeout(() => {
                    avatarUploadError.value = '';
                }, 3000);
            } finally {
                isAvatarUploading.value = false;
                // 重置文件输入
                event.target.value = '';
            }
        };

        // 更新用户头像信息到用户表
        const updateUserAvatar = async (avatarUrl) => {
            try {
                const updateData = {
                    id: getCurrentUserId(),
                    avatar: avatarUrl
                };

                await api.put('/user/user', updateData);

                // 重新加载用户信息以更新本地缓存
                await loadUserInfo();
            } catch (error) {
                console.error('更新用户头像信息失败:', error);
                // 这里可以选择不显示错误，因为头像已经上传成功，只是更新用户信息失败
            }
        };

        // 处理头像加载错误
        const handleAvatarError = () => {
            avatarUrl.value = '/imgs/default-avatar.png';
        };

        // 更新用户信息
        const updateUserInfo = async () => {
            errorMessage.value = '';
            successMessage.value = '';

            // 验证密码一致性
            if (password.value && password.value !== confirmPassword.value) {
                errorMessage.value = '两次输入的密码不一致';
                return;
            }

            // 验证手机号格式
            if (userInfo.value.phone && !/^1[3-9]\d{9}$/.test(userInfo.value.phone)) {
                errorMessage.value = '请输入正确的手机号格式';
                return;
            }

            try {
                isLoading.value = true;

                // 构建更新数据 - 从本地存储获取用户ID
                const updateData = {
                    id: getCurrentUserId(),
                    nickname: userInfo.value.nickname,
                    phone: userInfo.value.phone
                };

                // 如果填写了密码，则添加到更新数据中
                if (password.value) {
                    updateData.password = password.value;
                }

                // 发送更新请求 - 使用配置好的api实例
                const response = await api.put('/user/user', updateData);

                if (response.code === 1) {
                    successMessage.value = '用户信息更新成功';
                    // 清空密码输入框
                    password.value = '';
                    confirmPassword.value = '';
                    // 重新加载用户信息
                    await loadUserInfo();
                } else {
                    errorMessage.value = response.msg || '更新失败，请重试';
                }
            } catch (error) {
                errorMessage.value = '更新用户信息失败：' + (error.message || '未知错误');
                console.error('更新用户信息失败:', error);
            } finally {
                isLoading.value = false;
            }
        };

        // 处理登出
        const handleLogout = async () => {
            if (confirm('确定要退出登录吗？')) {
                try {
                    await logoutService();
                } catch (error) {
                    console.error('登出失败:', error);
                }
            }
        };

        // 组件挂载时加载用户信息
        onMounted(() => {
            loadUserInfo();
        });

        return {
            userInfo,
            password,
            confirmPassword,
            isLoading,
            errorMessage,
            successMessage,
            avatarUrl,
            isAvatarUploading,
            avatarUploadError,
            updateUserInfo,
            handleLogout,
            handleAvatarUpload,
            handleAvatarError
        };
    }
};
</script>

<style scoped>

.user-profile-container {
    max-width: 1000px;
    margin: 40px auto;
    padding: 20px;
    border-radius: 20px;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
    background: linear-gradient(-45deg, #f8f9ff, #eef3ff, #dce6ff, #f0f4ff);
    background-size: 400% 400%;
    animation: gradientBG 12s ease infinite;
}

/* 背景渐变动画 */
@keyframes gradientBG {
    0% {
        background-position: 0% 50%;
    }
    50% {
        background-position: 100% 50%;
    }
    100% {
        background-position: 0% 50%;
    }
}

.user-profile-header {
    margin-bottom: 40px;
    text-align: center;
}

.user-profile-header h2 {
    font-size: 32px;
    color: #333;
    margin-bottom: 10px;
    font-weight: 700;
}

.user-profile-header p {
    color: #666;
    font-size: 16px;
}

.user-profile-content {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 30px;
}

/* 卡片进场动画 */
.profile-form-card,
.security-actions-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.05);
    padding: 30px;
    opacity: 1;
    transform: none;

}

@keyframes cardFadeIn {
    to {
        opacity: 1;
        transform: translateY(0) scale(1);
    }
}

.profile-form-card:hover,
.security-actions-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.profile-form-card h3,
.security-actions-card h3 {
    font-size: 20px;
    color: #333;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 2px solid #7ed7e2;
}

/* 头像上传样式 */
.avatar-section {
    text-align: center;
    margin-bottom: 30px;
}

.avatar-uploader {
    display: inline-block;
    position: relative;
    margin-bottom: 10px;
}

.avatar-preview {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    overflow: hidden;
    cursor: pointer;
    border: 3px solid #e0e0e0;
    transition: all 0.3s ease;
}

.avatar-preview:hover {
    border-color: #5bb3ee;
    transform: scale(1.05);
}

.avatar-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.avatar-preview:hover .avatar-upload-overlay {
    opacity: 1;
}

.avatar-upload-overlay i {
    font-size: 24px;
    margin-bottom: 5px;
}

.avatar-input {
    display: none;
}

.avatar-hint {
    color: #666;
    font-size: 14px;
    margin-bottom: 10px;
}

.avatar-upload-progress {
    width: 200px;
    height: 4px;
    background-color: #e0e0e0;
    border-radius: 2px;
    overflow: hidden;
    margin: 0 auto;
}

.progress-bar {
    height: 100%;
    background-color: #5bb3ee;
    animation: progressAnimation 1.5s infinite ease-in-out;
}

@keyframes progressAnimation {
    0% {
        width: 0%;
    }
    50% {
        width: 70%;
    }
    100% {
        width: 100%;
    }
}

.error-message.small {
    font-size: 12px;
    padding: 5px 10px;
    margin-top: 5px;
}

/* 图标样式（这里使用简单的占位符） */
.icon-upload::before {
    content: "⇧";
}

.icon-logout::before {
    content: "⤫";
}

.icon-loading::before {
    content: "⟳";
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}

/* 输入框呼吸灯 */
.form-control:focus {
    outline: none;
    border-color: #63dbff;
    box-shadow: 0 0 8px rgba(99, 255, 247, 0.5);
    animation: pulseShadow 1.5s infinite alternate;
}

@keyframes pulseShadow {
    from {
        box-shadow: 0 0 8px rgba(99, 198, 255, 0.5);
    }
    to {
        box-shadow: 0 0 16px rgba(99, 232, 255, 0.8);
    }
}

/* 按钮悬停发光 */
.btn-primary:hover:not(:disabled) {
    background: #4ecbea;
    transform: translateY(-2px) scale(1.05);
    box-shadow: 0 0 20px rgba(99, 211, 255, 0.6);
}

/* 危险按钮闪烁效果 */
.btn-danger:hover {
    background: #e05656;
    transform: translateY(-2px) scale(1.05);
    box-shadow: 0 0 20px rgba(255, 107, 107, 0.6);
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    color: #444;
    font-weight: 500;
}

.form-control {
    width: 100%;
    padding: 12px 14px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 15px;
    transition: all 0.3s ease;
}

.form-control:focus {
    outline: none;
    border-color: #63d3ff;
    box-shadow: 0 0 8px rgba(99, 193, 255, 0.25);
}

.form-control:disabled {
    background-color: #f5f5f5;
    cursor: not-allowed;
}

.error-message {
    color: #e74c3c;
    margin-bottom: 15px;
    padding: 10px;
    background: #fee;
    border-radius: 6px;
    font-size: 14px;
}

.success-message {
    color: #2ecc71;
    margin-bottom: 15px;
    padding: 10px;
    background: #efe;
    border-radius: 6px;
    font-size: 14px;
}

.form-actions {
    margin-top: 25px;
}

.btn {
    padding: 12px 24px;
    border: none;
    border-radius: 30px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-primary {
    background: #5bb3ee;
    color: white;
    width: 250px;
    padding: 14px;
}

.btn-primary:hover:not(:disabled) {
    background: #4ea4ea;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(99, 185, 255, 0.3);
}

.btn-primary:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.btn-danger {
    background: #ff6b6b;
    color: white;
    width: 250px;
    padding: 14px;
}

.btn-danger:hover {
    background: #e05656;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .user-profile-content {
        grid-template-columns: 1fr;
    }

    .profile-form-card,
    .security-actions-card {
        padding: 20px;
    }

    .avatar-preview {
        width: 100px;
        height: 100px;
    }
}
</style>